package com.proyecto.core.vista.echo.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JasperRunManager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.proyecto.core.vista.echo.localizador.ServiceLocator;

public class ReporteGenerico extends HttpServlet {

	public ReporteGenerico() {super();}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    ServletContext sc = request.getSession().getServletContext();
	    HashMap<String, Object> hm = (HashMap<String, Object>) request.getSession().getAttribute("hm");
	    request.getSession().removeAttribute("hm");//Limipio la sesion
	    System.setProperty("jasper.reports.compile.temp", sc.getRealPath(hm.get("DIRECTORIO").toString()));
	    File reportFile = new File(sc.getRealPath(hm.get("DIRECTORIO").toString() + hm.get("NOMBRE_REPORTE") + ".jasper"));
	    String sessionFactory = null==hm.get("sessionFactory")?"SessionFactoryBean":hm.get("sessionFactory").toString();
	    Session sesion = ((SessionFactory) (new ServiceLocator(sc)).getBean(sessionFactory)).openSession();
	    try {
		    byte[] bytes = null;
		    bytes =  JasperRunManager.runReportToPdf(reportFile.getPath(), hm, sesion.connection());
		    response.setContentType("application/pdf");
		    response.setContentLength(bytes.length);
		    ServletOutputStream ouputStream = response.getOutputStream();
		    ouputStream.write(bytes, 0, bytes.length);
		    ouputStream.flush();
		    ouputStream.close();	
	    }catch (Exception e) {e.printStackTrace();
		}finally{sesion.close();}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>Error</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    Ha ocurrido un error al intentar cargar el servlet de reportes ");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	public void init() throws ServletException {
	}

}